/*
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cheyun.netsalev3.utils

import android.annotation.SuppressLint
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
//import android.icu.text.SimpleDateFormat
import android.text.Html
import android.text.InputType
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import androidx.databinding.OnRebindCallback
import androidx.databinding.ViewDataBinding
import androidx.transition.ChangeBounds
import androidx.transition.Slide
import androidx.transition.TransitionManager
import androidx.transition.TransitionSet
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.*
import com.cheyun.netsalev3.bean.records.Follow
import com.cheyun.netsalev3.bean.records.PurchaseInfo
import com.cheyun.netsalev3.bean.records.Transfer
import com.cheyun.netsalev3.databinding.CarItemBinding
import com.cheyun.netsalev3.databinding.CustomerItemAddviewBinding
import com.cheyun.netsalev3.databinding.HomeAnalysisTopItemBinding
import com.cheyun.netsalev3.viewmodel.BaseViewModel
import com.cheyun.netsalev3.widget.*
import com.google.android.material.card.MaterialCardView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.text.SimpleDateFormat
import java.util.*

@BindingAdapter("imageFromUrl")
fun bindImageFromUrl(view: ImageView, imageUrl: String?) {
    if (!imageUrl.isNullOrEmpty()) {
        Glide.with(view.context)
                .load(imageUrl)
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(view)
    }
}

@BindingAdapter("isGone")
fun bindIsGone(view: FloatingActionButton, isGone: Boolean?) {
    if (isGone == null || isGone) {
        view.hide()
    } else {
        view.show()
    }
}

@BindingAdapter("myStrokeColor")
fun myStrokeColor(view: MaterialCardView, isSelect: Boolean) {
    if (isSelect) {
        view.strokeColor = ContextCompat.getColor(view.context, R.color.diolg2)
    } else {
        view.strokeColor = ContextCompat.getColor(view.context, R.color.transparent)
    }
}


@BindingAdapter("mytext")
fun bindMyText(view: TextView, myData: MyData) {
//    var ss = "·今日到店&ensp;" + "<font color=\"#546478\">" + FunctionUtils.stringLeng("1") + "</font>&ensp;&ensp;" +
//            "·今日订车&ensp;" + "<font color=\"#546478\">" + FunctionUtils.stringLeng("10") + "</font>&ensp;&ensp;" +
//            "·今日提车&ensp;" + "<font color=\"#546478\">" + FunctionUtils.stringLeng("100") + "</font><br>" +
//            "·等待跟进&ensp;" + "<font color=\"#546478\">" + FunctionUtils.stringLeng("100000") + "</font>&ensp;&ensp;" +
//            "·已经跟进&ensp;" + "<font color=\"#546478\">" + FunctionUtils.stringLeng("10000") + "</font>&ensp;&ensp;" +
//            "·逾期跟进&ensp;" + "<font color=\"#546478\">" + FunctionUtils.stringLeng("100000") + "</font><br>" +
//            "·虚假战败&ensp;" + "<font color=\"#546478\">" + FunctionUtils.stringLeng("100000") + "</font>"
    view.text = Html.fromHtml(myData.conttString)

}

@BindingAdapter("myHometext")
fun myHometext(view: TextView, p: Transfer) {
    if (p.ownername_old == "" || p.ownername_new == p.ownername_old) {
        view.text = "拥有者：" + p.ownername_new
    } else if (p.ownername_new != p.ownername_old) {
        view.text = "拥有者：" + p.ownername_old + "——>" + p.ownername_new
    }


}

//@BindingAdapter("myRecordShow")
//fun myRecordShow(view: View, p: Follow) {
//    if (p.arrive_info.arrivetime == null) {
//        view.visibility = View.GONE
//    } else {
//        view.visibility = View.VISIBLE
//    }
//}

/**
 * 客户状态
 */
@BindingAdapter("customerStatus")
fun customerStatus(view: LinearLayout, p: ClueDetails?) {
    p?.apply {
        view.removeAllViews()
        if (driving == "1") {
            var binding = CarItemBinding.inflate(LayoutInflater.from(view.context), null, false)
            binding.nameText.text = "试驾"
            view.addView(binding.root)
        }
        if (arrive == "1") {
            var binding = CarItemBinding.inflate(LayoutInflater.from(view.context), null, false)
            binding.nameText.text = "到店"
            view.addView(binding.root)
        }
    }


}

@BindingAdapter("isExpand")
fun bindMyExpand(view: View, param: MyData) {
    view.setOnClickListener {
        if (param != null) {
            param.IsSelect = !param.IsSelect!!
        }
    }
}

private var rotateAnimation1: Animation? = null
private var rotateAnimation2: Animation? = null

@BindingAdapter("myRotate")
fun bindMyRotate(view: View, isSelect: Boolean) {
    if (view.tag == null) {
        view.tag = true
    }
    if (rotateAnimation1 == null) {
        rotateAnimation1 = AnimationUtils.loadAnimation(view.context, R.anim.rotate_anim)
    }
    if (rotateAnimation2 == null) {
        rotateAnimation2 = AnimationUtils.loadAnimation(view.context, R.anim.rotate_anim_2)
    }
    if (!isSelect) {
        view.startAnimation(rotateAnimation2)
    } else {
        view.startAnimation(rotateAnimation1)
    }
}

@BindingAdapter("myJianBianColor")
fun bindMyJianBianColor(view: ViewGroup, color: Drawable) {
    var position = 0
    for (i in 0 until view.childCount) {
        var temview = view.getChildAt(i)
        if (temview is LinearLayout) {
            if (position % 2 == 1) {
                temview.background = color
            } else {
                temview.background = ColorDrawable(view.context.resources.getColor(R.color.white))
            }
            position++
        }
    }
}

@BindingAdapter("myRelayoutJianBianColor")
fun bindMyJianBianRelayoutColor(view: ViewGroup, color: Drawable) {
    var position = 0
    for (i in 0 until view.childCount) {
        var temview = view.getChildAt(i)
        if (temview is RelativeLayout) {
            if (position % 2 == 1) {
                temview.background = color
            } else {
                temview.background = ColorDrawable(view.context.resources.getColor(R.color.white))
            }
            position++
        }
    }
}

@BindingAdapter("mystockstate")
fun mystockstate(view: TextView, state: Int) {
//    state		库存状态 1 => '在途',2 => '预定',3 => '在库',4 => '出库',5 => '配车'
    when (state) {
        1 -> view.text = "在途"
        2 -> view.text = "预定"
        3 -> view.text = "在库"
        4 -> view.text = "出库"
        5 -> view.text = "配车"
    }
}

/**
 * 添加UI变动动画
 */
@BindingAdapter("addOnRebindCallback")
fun bindAddOnRebindCallback(view: View, binding: ViewDataBinding) {
    binding.addOnRebindCallback(object : OnRebindCallback<ViewDataBinding>() {
        override fun onPreBind(binding: ViewDataBinding?): Boolean {

            var transform = TransitionSet()
            transform.ordering = TransitionSet.ORDERING_TOGETHER
            transform.addTransition(Slide(Gravity.TOP))
                    .addTransition(ChangeBounds())
            TransitionManager.beginDelayedTransition(
                    binding!!.root as ViewGroup, transform)
            return super.onPreBind(binding)
        }
    })
}

/**
 * 动态向LinearLayout添加view
 */
@BindingAdapter("addview")
fun bindaddView(view: LinearLayout, item: Row) {

    if (view.childCount > 0) {
        view.removeAllViews()
    }
    if (item.hashMap?.values == null) {
        return
    }
    for (i in item.hashMap.values) {
        if (i.id == -1) {
            var bingding = CustomerItemAddviewBinding.inflate(LayoutInflater.from(view.context), null, false)
            bingding.item = i
            view.addView(bingding.root)
        }
        if (i.IsSelect && i.id != -1) {
            var bingding = CustomerItemAddviewBinding.inflate(LayoutInflater.from(view.context), null, false)
            bingding.item = i
            view.addView(bingding.root)
        }
    }
}

@BindingAdapter("bindClueItem")
fun bindClueItem(view: ClueItemView, item: Row) {
    view.setData(item)
}

/**
 * 动态向LinearLayout添加view
 */
@BindingAdapter("addview2")
fun bindaddView2(view: LinearLayout, list: List<AnalysisParam>?) {
    if (view.childCount > 0) {
        view.removeAllViews()
    }
    list?.apply {

        for (i in 0 until this.size) {
            var bingding = HomeAnalysisTopItemBinding.inflate(LayoutInflater.from(view.context), null, false)
            var param = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
            if (this.size == 1) {
                bingding.position = 2
            } else {
                bingding.position = i
            }
            bingding.item = this[i]
            bingding.root.layoutParams = param
            view.addView(bingding.root)
        }
    }


}

@BindingAdapter("MydrawableLeft")
fun myDrawableLeft(view: TextView, drawableid: Int) {
    var drawable = MyApplication.getInstance().getDrawable(drawableid)
    setIntrinsicBounds(drawable)
    val drawables = view.compoundDrawables
    view.setCompoundDrawables(drawable, drawables[1], drawables[2], drawables[3])
}

@BindingAdapter("MydrawableTop")
fun MydrawableTop(view: TextView, drawableid: Int) {
    var drawable = MyApplication.getInstance().getDrawable(drawableid)
    setIntrinsicBounds(drawable)
    val drawables = view.compoundDrawables
    view.setCompoundDrawables(drawables[0], drawable, drawables[2],
            drawables[3])
}


private fun setIntrinsicBounds(drawable: Drawable?) {
    drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
}

@SuppressLint("NewApi")
@BindingAdapter(value = ["myStartTime", "myEndTime"])
fun myTime(view: TextView, s: kotlin.Long, d: kotlin.Long) {
    val format = SimpleDateFormat("yyyy-MM-dd")
    val start = format.format(Date(s*1000))
    val end = format.format(Date(d*1000))
    view.text = start + "——" + end
}

@SuppressLint("NewApi")
@BindingAdapter(value = ["myTimespanTime"])
fun myUnixTimespan(view: TextView, s: kotlin.String) {
    val format = SimpleDateFormat("yyyy-MM-dd HH:mm")
    var time = ""
    if(s.length == 13){
        time = format.format(Date(s.toLong()))
    }else{
        time = format.format(Date(s.toLong()*1000))
    }
    view.text = time
}

@BindingAdapter(value = ["brandName","seriesName", "specName"])
fun myCarName(view: TextView, b: kotlin.String, s: kotlin.String,sp: kotlin.String) {
    view.text = b + "  "+ s+"  " + sp
}

/**
 * 修改自定义圆环属性
 */
@BindingAdapter(value = ["myCircleViewText", "myCircleViewPosition"])
fun myCircleViewText(view: MyCircleView, text: String, pos: Int) {
    when (pos) {
        0 -> view.setText("#ff419bfc", text.toFloat() / 100)
        1 -> view.setText("#ffff5a82", text.toFloat() / 100)
        2 -> view.setText("#ff00c2de", text.toFloat() / 100)
    }

}


/**
 * heiview右边点击事件
 */
@BindingAdapter("headViewRightListener")
fun bindHeadViewRightListener(view: HeadView, clickListener: View.OnClickListener) {
    view.rightBut?.setOnClickListener(clickListener)
}

@BindingAdapter("android:layout_marginTop")
fun setMarginTop(view: View, marginFloat: Float) {
    val margin = pixelsToDimensionPixelSize(marginFloat)
    var param = view.layoutParams as ViewGroup.MarginLayoutParams
    param.topMargin = margin
    view.layoutParams = param
}

@BindingAdapter("android:layout_marginBottom")
fun setMarginBottom(view: View, marginFloat: Float) {
    val margin = pixelsToDimensionPixelSize(marginFloat)
    var param = view.layoutParams as ViewGroup.MarginLayoutParams
    param.bottomMargin = margin
    view.layoutParams = param
}


private fun pixelsToDimensionPixelSize(pixels: Float): Int {
    val result = (pixels + 0.5f).toInt()
    return when {
        result != 0 -> result
        pixels == 0f -> 0
        pixels > 0 -> 1
        else -> -1
    }
}

/**
 * 首页显示条目
 */
@BindingAdapter(value = ["homeCunt", "hometype"], requireAll = true)
fun myHomeCount(view: TextView, p: PersonlistParam?, type: Int) {
    //今日到店0 今日联系1
    when (type) {
        0 -> view.text = "（ ${p?.arrive_total ?: 0}条 ）"
        1 -> view.text = "（ ${p?.connect_total ?: 0}条 ）"
    }
}


/**
 * 开关
 */
@BindingAdapter("mySwitch")
fun mySwitch(view: Switch, i: Int) {
    view.isChecked = i == 1
}

/**
 * 线索详情线索显示隐藏相关
 */
@BindingAdapter("myDefeatDetails")
fun myDefeatDetails(view: View, i: String?) {
    i?.apply {
        if (i == "0" || i == "") {
            view.visibility = View.GONE
        } else {
            view.visibility = View.VISIBLE
        }
    }

}

/**
 * 线索明细显示隐藏相关
 */
@BindingAdapter("myDetailsMx1")
fun myDefeatDetails1(view: View, i: String?) {
    i?.apply {
        if (i == "mor") {
            view.visibility = View.VISIBLE
        } else {
            view.visibility = View.GONE
        }
    }

}

/**
 * 线索明细显示隐藏相关
 */
@BindingAdapter("myDetailsMx2")
fun myDefeatDetails2(view: View, i: String?) {
    i?.apply {
        if (i == "mor") {
            view.visibility = View.GONE
        } else {
            view.visibility = View.VISIBLE
        }
    }

}

/**
 * 线索详情线索显示隐藏相关
 */
@BindingAdapter("aligntext")
fun aligntext(view: AlignTextView, i: String) {
    view.setAlingText(i)
}

/**i
 * 名称截取
 */
@BindingAdapter("myname")
fun myname(view: TextView, i: String?) {
    i?.apply {
        if (i.length > 2) {
            view.text = i.substring(i.length - 2)
        } else {
            view.text = i
        }
    }

}


@BindingAdapter("myinputType")
fun myinputType(view: EditText, i: KeyValueParam?) {
    i?.apply {
        view.isFocusable = i.isEdit

        if (i.type == 2 && i.sontype == 1) {
//            view.inputType = InputType.TYPE_NUMBER_FLAG_DECIMAL
        } else {
            view.inputType = InputType.TYPE_CLASS_TEXT
        }

    }


}

@BindingAdapter("myfocusable")
fun myfocusable(view: EditText, myfocusable: Boolean) {

    view.isFocusable = myfocusable

}

/**i
 * 潜客数据状态
 */
@BindingAdapter("mystate")
fun mystate(view: TextView, i: String?) {
//31 => '潜客(转出)',32 => '潜客(战败)',33 => '潜客(无效)
    if (i.isNullOrBlank()) {
        view.visibility = View.GONE
    } else {
        view.visibility = View.VISIBLE
        when (i) {
            "31" -> view.text = "转出"
            "32" -> view.text = "战败"
            "33" -> view.text = "无效"
            else -> view.visibility = View.GONE
        }
    }
}


@BindingAdapter("radioData")
fun bindRadioData(view: View, param: ArrayList<DialogParam>) {
    (view as RadioGroupView).setData(param)
}

@BindingAdapter("radioColumn")
fun bindRadioColumn(view: View, param: Int) {
    (view as RadioGroupView).setColumn(param)
}

@BindingAdapter("radioLine")
fun bindRadioLine(view: View, param: Int) {
    (view as RadioGroupView).setLine(param)
}

@BindingAdapter("radioMaxCount")
fun bindRadioMaxCount(view: View, param: Int) {
    (view as RadioGroupView).setMaxCount1(param)
}

@BindingAdapter("radioInitValue")
fun bindRadioValue(view: View, param: String) {
    (view as RadioGroupView).setDefaultValue(param)
}


@BindingAdapter("radioLock")
fun bindRadioLock(view: View, param: Boolean) {
    (view as RadioGroupView).lockClick(param)
}

@BindingAdapter("radioPosition")
fun bindRadioPosition(view: View, param: Any) {
    (view as RadioGroupView).setPosition(param)
}

@BindingAdapter("radioModel")
fun bindRadioModel(view: View, viewModel: BaseViewModel) {
    (view as RadioGroupView).bindViewModel(viewModel)
}

@BindingAdapter("mySrc")
fun setImage(view: View, img: String) {
    (view as MyImageView).setImage(img)
}
@BindingAdapter("srcRadius")
fun setImageRound(view: View, radius: String) {
    (view as MyImageView).setImageRound(radius)
}



















